<?php


namespace app\service;


use app\entity\ActTypeEntity;
use app\exception\ErrorCode;
use app\exception\OaException;
use app\models\request\ReqDel;
use app\models\request\ReqTypeAdd;
use app\models\request\ReqTypeList;
use yii\data\Pagination;

class TypeService
{

    public function listPage(ReqTypeList  $req) {
        $data = ActTypeEntity::find()->where(["del_flag"=>0])->orderBy("id asc");
        $pages = new Pagination(['totalCount' =>$data->count(), 'pageSize' => $req->getPageSize(),'page'=>$req->getPageNo()-1]);
        /**@var $entities ActTypeEntity[]*/
        $entities = $data->offset($pages->getOffset())->limit($pages->getLimit())->all();
        $list = [];
        foreach ($entities as $entity) {
            $resp = [
                "id"=>$entity->getId(),
                "name"=>$entity->getName(),
                "type"=>$entity->getType(),
                "remark"=>$entity->getRemark(),
                "create_time"=>$entity->getCreateTime(),
                "update_time"=>$entity->getUpdateTime(),
            ];
            array_push($list,$resp);
        }

       return  [
           "total"=>intval($pages->totalCount),
           "pageSize"=>($pages->getPageSize()),
           "pageNo"=>($req->getPageNo()),
           "list"=>$list,
        ];
    }

    /**
     * @param $id
     * @return array|\yii\db\ActiveRecord|ActTypeEntity
     * @throws OaException
     */
    public function findByPk($id){
        $entity = ActTypeEntity::find()->where(["id"=>$id])->one();
        if (!$entity){
            throw new OaException(ErrorCode::NOT_404);
        }
        return $entity;
    }

    /**
     * @param ReqTypeAdd $req
     * @return bool
     * @throws OaException
     */
    public function add(ReqTypeAdd $req) {
        if ($req->getId()) {
            $entity = $this->findByPk($req->getId());
        } else {
            $entity = new ActTypeEntity();
            $entity->setCreateTime(date("Y-m-d G:i:s"));
            $entity->setDelFlag(0);
        }
        $entity->setUpdateTime(date("Y-m-d G:i:s"));
        $entity->setName($req->getName());
        $entity->setType($req->getType());
        $entity->setRemark($req->getRemark());
        $entity->save();
        return true;
    }

    /**
     * @param ReqDel $req
     * @return bool
     * @throws OaException
     */
    public function del(ReqDel $req) {
        $entity = $this->findByPk($req->getId());
        $entity->setDelFlag(0);
        $entity->save();
        return true;
    }
}